<template>
  <BaseMainSlot
    :show-tab="true"
  >
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:tab-select>
      <selectbutton
        :buttonselectlist="buttonselectlist"
        @nowselectbuttonindex="nowselectbuttonindex"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(76, 'edit') && forderStatus === 0"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'edit') && forderStatus === 0"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="check(row)"
            >
              <i class="el-icon-edit-outline"></i>审核
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete') && forderStatus === 0"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.orderNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button
              v-if="judgePermission(76, 'edit') && forderStatus !== 0"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="check(row)"
            >
              <i class="el-icon-view"></i>查看详情
            </el-button>
          </template>
        </template>
        <template v-slot:completeStatus="{ row, item }">
          <span v-if="item.prop === 'completeStatus'">{{ row[item.prop] ? '完成':'未完成' }}</span>
          <span v-else>{{ row[item.prop] || '——' }}</span>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <!-- 添加 -->
          <el-form-item
            v-for="item,index in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.type === 'Select'? item.selectValue : item.prop"
            class="w50p"
            :rules="item.isCheck ? rules[item.prop]:[
              { required: item.required, message: item.name + '不能为空', trigger: item.type === 'input'? 'blur' : 'change'}
            ]"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[ `${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
              :disabled="nowChanceStau === 'check' || item.prop === 'orderNo' || item.prop === 'totalNumber'"
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.selectValue}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
              :disabled="nowChanceStau === 'check'"
              @change="getCoustomer($event,item.prop)"
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items.name"
                :value="items.value"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.prop}`]"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm"
              :placeholder="'选择' + item.name"
              :disabled="nowChanceStau === 'check'"
            />
          </el-form-item>
          <el-divider content-position="left">采购订单明细</el-divider>
          <!-- 循环明细 -->
          <div
            v-for="orderDetail,index in formData.orderDetailList"
            :key="orderDetail.key"
            class="w100p xunhuan"
          >
            <div class="w100p goods">采购商品{{ index + 1 }}</div>
            <el-form-item
              label="商品名称 :"
              :prop="'orderDetailList.' + index + '.materialNo'"
              class="w50p"
              :rules="[{required: true,message:'商品名称不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.materialNo"
                placeholder="请选择商品（物料）名称"
                clearable
                :disabled="nowChanceStau === 'check'"
                @change="getGoods($event,index)"
              >
                <el-option
                  v-for="items,indexs in materialList"
                  :key="indexs"
                  :label="items.materialName"
                  :value="items.materialNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="收货仓库 :"
              :prop="'orderDetailList.' + index + '.stordocNo'"
              class="w50p"
            >
              <el-select
                v-model="orderDetail.stordocNo"
                placeholder="请选择收货仓库"
                clearable
                :disabled="nowChanceStau === 'check'"
              >
                <el-option
                  v-for="items,indexs in stordocList"
                  :key="indexs"
                  :label="items.stordocName"
                  :value="items.stordocNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="采购数量 :"
              :prop="'orderDetailList.' + index + '.confirmQuantity'"
              class="w50p numberUnit"
              :rules="[{required: true,message:'数量不能为空',trigger:'blur'},{pattern: /^\d+$/,message:'值该为正整数',trigger: ['change','blur']},
              ]"
            >
              <el-input
                v-model="orderDetail.confirmQuantity"
                clearable
                class="one"
                placeholder="请输入数量"
                :disabled="nowChanceStau === 'check'"
                @change="countOnePrice($event,index)"
              />
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="请选择单位"
                class="two"
                clearable
                :disabled="nowChanceStau === 'check'"
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol||items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              label="单位 :"
              :prop="'orderDetailList.' + index + '.castUnitNo'"
              class="w50p"
              :rules="[{required: true,message:'单位不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="请选择单位"
                clearable
                :disabled="nowChanceStau === 'check'"
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol||items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="换算率 :"
              :prop="'orderDetailList.' + index + '.exchangeRate'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']},
                       {required: true,message:'换算率不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.exchangeRate"
                clearable
                placeholder="请输入换算率"
                :disabled="nowChanceStau === 'check'"
              />
            </el-form-item>
            <div class="zhu w50p">
              <el-form-item
                label="主数量&主单位 :"
                :prop="'orderDetailList.' + index + '.primaryQuantity'"
                style="width: 82%;"
                :rules="[{required: true,message:'数量不能为空',trigger:'blur'},{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']},
                ]"
              >
                <el-input
                  v-model="orderDetail.primaryQuantity"
                  clearable
                  disabled
                  placeholder="请输入主数量"
                />
              </el-form-item>
              <el-form-item
                :prop="'orderDetailList.' + index + '.unitNo'"
                style="width: 18%;"
                :rules="[{required: true,message:'主单位不能为空',trigger:'change'}]"
              >
                <el-select
                  v-model="orderDetail.unitNo"
                  placeholder="请选择单位"
                  disabled
                  clearable
                >
                  <el-option
                    v-for="items,indexs in unitList"
                    :key="indexs"
                    :label="items.symbol||items.unitName"
                    :value="items.unitNo"
                  />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item
              label="单价/元 :"
              :prop="'orderDetailList.' + index + '.price'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']},
                       {required: true,message:'单价不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.price"
                clearable
                placeholder="请输入单价"
                :disabled="nowChanceStau === 'check'"
                @change="countOnePrice($event,index)"
              />
            </el-form-item>

            <el-form-item
              label="折扣/折 :"
              :prop="'orderDetailList.' + index + '.discount'"
              class="w50p"
              :rules="{pattern: /^\d(\.\d)?$/ , message: '数字不能小于0大于10且只能有一位小数', trigger: ['change','blur']}"
            >
              <el-input
                v-model="orderDetail.discount"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入数量"
                @change="countOnePrice($event,index)"
              />
            </el-form-item>

            <el-form-item
              label="折扣额/元 :"
              :prop="'orderDetailList.' + index + '.discountPrice'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']}]"
            >
              <el-input
                v-model="orderDetail.discountPrice"
                :disabled="nowChanceStau === 'check'"
                clearable
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="件数 :"
              :prop="'orderDetailList.' + index + '.packNum'"
              class="w50p"
              :rules="[{pattern: /^\d+$/,message:'值该为正整数',trigger: ['change','blur']},
                       {required: true,message:'单价不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.packNum"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="价税合计/元 :"
              :prop="'orderDetailList.' + index + '.totalPrice'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']},
                       {required: true,message:'价税合计不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.totalPrice"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入金额"
              />
            </el-form-item>

            <!-- <el-form-item
              label="重量/kg :"
              :prop="'orderDetailList.' + index + '.weight'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']}]"
            >
              <el-input
                v-model="orderDetail.weight"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入重量"
              />
            </el-form-item>-->

            <el-form-item
              label="体积/L :"
              :prop="'orderDetailList.' + index + '.volume'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message:'值为大于0的数', trigger: ['change','blur']}]"
            >
              <el-input
                v-model="orderDetail.volume"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入体积"
              />
            </el-form-item>

            <el-form-item
              label="收货地址 :"
              :prop="'orderDetailList.' + index + '.address'"
              class="w50p"
              :rules="[{required: true,message:'收货地址不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.address"
                placeholder="请选择收货地址"
                clearable
                :disabled="nowChanceStau === 'check'"
              >
                <el-option
                  v-for="items,indexs in addressList"
                  :key="indexs"
                  :label="items.spliceAddress"
                  :value="items.spliceAddress"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="预计到货时间 :"
              :prop="'orderDetailList.' + index + '.arrivalTime'"
              class="w50p"
            >
              <el-date-picker
                v-model="orderDetail.arrivalTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                clearable
                placeholder="请选择时间"
                :disabled="nowChanceStau === 'check'"
              />
            </el-form-item>

            <el-form-item
              label="操作员 :"
              :prop="'orderDetailList.' + index + '.chandlerName'"
              class="w50p"
            >
              <el-input
                v-model="orderDetail.chandlerName"
                clearable
                :disabled="nowChanceStau === 'check'"
                placeholder="请输入操作员"
              />
            </el-form-item>
            <div class="editBox">
              <el-button
                v-if="nowChanceStau === 'edit' && !orderDetail.orderNo"
                type="primary"
                @click="addDetail({...orderDetail,orderNo:formData.orderNo},index)"
              >添加</el-button>
              <el-button
                v-if="nowChanceStau === 'edit' && orderDetail.orderNo"
                type="warning"
                @click="editDetail(orderDetail)"
              >修改</el-button>
              <el-button
                v-if="nowChanceStau === 'edit' && orderDetail.orderNo"
                type="danger"
                @click="delDetial(orderDetail,index)"
              >删除</el-button>
              <el-button
                v-if="!orderDetail.orderNo"
                type="info"
                circle
                @click="delOrderDetail(index)"
              >
                <i class="el-icon-minus"></i>
              </el-button>
            </div>
          </div>
          <div>
            <el-button
              v-if="nowChanceStau !== 'check'"
              class="addone"
              type="info"
              circle
              @click="addOrderDetail"
            >
              <i class="el-icon-plus"></i>
            </el-button>
          </div>
          <!-- 汇总 -->
          <div class="w100p xunhuan">
            <el-divider content-position="left">明细合计</el-divider>
            <el-form-item label="总数量 :" prop="totalQuantity" class="w50p">
              <el-input
                v-model="formData.totalQuantity"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>
            <!-- <el-form-item label="总重量/kg :" class="w50p">
              <el-input
                v-model="formData.totalWeight"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>-->
            <!-- <el-form-item label="总体积/L :" class="w50p">
              <el-input
                v-model="formData.totalVolume"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>-->
            <el-form-item label="价税合计/元 :" prop="totalPrice" class="w50p">
              <el-input
                v-model="formData.totalPrice"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>

            <el-form-item label="备注 :" class="w50p">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                row="2"
                placeholder="请备注"
              />
            </el-form-item>
            <el-divider
              v-if="nowChanceStau === 'check'"
              content-position="left"
            >审核</el-divider>
            <el-form-item
              v-if="nowChanceStau === 'check'"
              label="审核状态 :"
              prop="forderStatus"
              class="w50p"
              :rules="[ {required: true,message:'审核状态不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="formData.forderStatus"
                placeholder="请选择审核状态"
                clearable
              >
                <el-option
                  v-for="items,indexs in checkList"
                  :key="indexs"
                  :label="items.name"
                  :value="items.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="nowChanceStau === 'check'"
              label="审批日期 :"
              prop="forderStatus"
              class="w50p"
              :rules="[ {required: true,message:'审核日期不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="formData.approvalTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择审批时间"
              />
            </el-form-item>

            <el-form-item
              v-if="nowChanceStau === 'check'"
              label="审核人 :"
              prop="approverName"
              class="w50p"
              :rules="[ {required: true,message:'审核人不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="formData.approverName"
                placeholder="请选择审核状态"
                clearable
              />
            </el-form-item>
          </div>
        </el-form>
        <div
          v-if="nowChanceStau !== ''"
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="cancel('formData')"
          >取 消</el-button>
          <el-button
            v-if="forderStatus === 0"
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import selectbutton from "@/components/selectbutton/index.vue";
import { mymixin } from "@/utils/mixins";
import supplierApi from "@/api/livestock-manage/purchaseManage/supplier";
import unitApi from "@/api/basic-info-manage/unit-manage";
// import materialApi from "@/api/basic-info-manage/material/material-manage";
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage";
import orderApi from "@/api/livestock-manage/purchaseManage/purchaseOrder";
import orderDetailApi from "@/api/livestock-manage/purchaseManage/orderDetail";
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
// import nowpagereqquery from "@/api/livestock-manage/production-batch-manage/production-batch-query";
import nowpagereqquery from "@/api/digital-production/production-batch-manage/create-production-batch/index";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: {
    SearchForm,
    Table,
    ActionBar,
    Pagination,
    BaseMainSlot,
    selectbutton
  },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '采购订单编号',
          prop: 'orderNo',
          type: 'input',
        },
        {
          label: '供应商名称',
          prop: 'supplierNo',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '采购员',
          prop: 'buyerName',
          type: 'input',
        },
        {
          label: '审批人',
          prop: 'approverName',
          type: 'input',
        },
        {
          label: '订单日期',
          prop: 'orderTime',
          type: 'date',
        },
      ],
      forderStatus: 0,
      selectedStaffList: [],
      addressList: [],
      stordocList: [],
      unitList: [],
      materialList: [],
      checkList: [
        { name: "未审核", value: 0 },
        { name: "审批通过", value: 1 },
        { name: "审批不通过", value: 2 }
      ],
      formData: {
        orderDetailList: [
          {
            address: "",
            arrivalTime: "",
            castUnitNo: "",
            chandlerName: "",
            confirmQuantity: "",
            discount: "",
            discountPrice: "",
            materialNo: "",
            primaryQuantity: "",
            packNum: "",
            price: "",
            stordocNo: "",
            totalPrice: "",
            unitNo: "",
            exchangeRate: "",
            volume: "",
            weight: ""
          }
        ]
      },
      buttonselectlist: [
        { name: "未审核" },
        { name: "审核通过" },
        { name: "审核未通过" }
      ],
      // selectValue 用于传递select的编号
      formDatalist: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          typeObj: {},
          name: "采购订单编号",
          required: true
        },
        {
          type: "date",
          prop: "orderTime", // input Select Checkbox TimePicker
          typeObj: {},
          name: "订单日期",
          required: true
        },
        {
          type: "Select",
          prop: "supplierName",
          selectValue: "supplierNo",
          typeObj: {},
          name: "供应商",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "buyerName",
          typeObj: {},
          name: "采购员",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bankAccount",
          typeObj: {},
          name: "银行账号",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bank",
          typeObj: {},
          name: "开户银行",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "shippingAddress",
          typeObj: {},
          name: "供应商发货地址",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "approverName",
          typeObj: {},
          name: "审批人",
          required: true
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "approvalTime",
          typeObj: {},
          name: "审批日期",
          required: true,
          notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalQuantity",
          typeObj: {},
          name: "总数量",
          required: true
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "totalWeight",
        //   typeObj: {},
        //   name: "总重量/kg",
        //   required: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "totalVolume",
        //   typeObj: {},
        //   name: "总体积/L",
        //   required: true
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "价税合计/元",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          // required: true,
          notSearch: true
        }
      ],
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          typeObj: {},
          name: "采购订单编号",
          required: true
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "orderTime",
          typeObj: {},
          name: "订单日期",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "buyerName",
          typeObj: {},
          name: "采购员",
          required: true
        },
        {
          type: "Select",
          prop: "supplierName",
          selectValue: "supplierNo",
          typeObj: {},
          name: "供应商",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bankAccount",
          typeObj: {},
          name: "银行账号",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bank",
          typeObj: {},
          name: "开户银行",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "shippingAddress",
          typeObj: {},
          name: "供应商发货地址",
          required: true
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "approverName",
        //   typeObj: {},
        //   name: "审批人",
        //   required: true
        // },
        // {
        //   type: "TimePicker", // input Select Checkbox TimePicker
        //   prop: "approvalTime",
        //   typeObj: {},
        //   name: "审批日期",
        //   required: true
        // },
        // {
        //   type: "Select", // input Select Checkbox TimePicker
        //   prop: "completeStatus",
        //   selectValue: "completeStatus",
        //   typeObj: {
        //     list: [
        //       { name: "未完成", value: false },
        //       { name: "已完成", value: true }
        //     ]
        //   },
        //   name: "完成状态",
        //   required: true
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true
        }
      ],
      rules: {}
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.orderDetailList) {
          val.totalQuantity = sum(
            val.orderDetailList.map(item => item.confirmQuantity || 0)
          );
          val.totalVolume = sum(
            val.orderDetailList.map(item => item.volume || 0)
          );
          val.totalWeight = sum(
            val.orderDetailList.map(item => item.weight || 0)
          );
          val.totalPrice = sum(
            val.orderDetailList.map(item => item.totalPrice || 0)
          );
          val.totalNumber = sum(
            val.orderDetailList.map(item => item.packNum || 0)
          );
        }
        function sum(arr) {
          let s = 0;
          for (let i = arr.length - 1; i >= 0; i--) {
            s += parseInt(arr[i]);
          }
          return s;
        }
        // sum(val.orderDetailList.map(item => item.confirmQuantity))
      }
    }
  },
  created() {
    let list = []
    this.formDatalist.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      el.prop == 'completeStatus' && (obj.slotName = 'completeStatus')
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '200' })
    this.tableColumn = list

    this.search();
    this.getSupplierList();
    this.getMaterialList();
    this.getstordocList();
    this.getAddressList();
    this.getUnitList();
  },
  methods: {
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 获取地址
    getAddressList() {
      addressApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.addressList = res.data;
        }
      });
    },
    // 获取仓库
    getstordocList() {
      warehouseApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.stordocList = res.data;
        }
      });
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then(res => {
        if (res.code === 1) {
          this.materialList = res.data;
        }
      });
    },
    // 获取单位列表
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then(res => {
        console.log(res.data)
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 获取供应商
    getSupplierList() {
      supplierApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach(item => {
            list.push({
              name: item.supplierName,
              value: item.supplierNo
            });
          });
          this.setOptions(this.formConfig, 'supplierNo', list)
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "supplierName") {
              this.$set(this.formDatalists[index], "typeObj", { list: list });
            }
          });
          this.formDatalist.forEach((item, index) => {
            if (item.prop === "supplierName") {
              this.$set(this.formDatalist[index], "typeObj", {
                list: list,
                listName: ["name", "value"]
              });
            }
          });
        }
      });
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then(res => {
        this.formData.orderDetailList[index].unitNo = res.data[0].unitNo;
        this.formData.orderDetailList[index].castUnitNo = res.data[0].unitNo;
      });
    },
    // 获取单个供应商
    getCoustomer(event, prop) {
      if (prop === "supplierName") {
        console.log(event, prop);
        supplierApi.conditionQuery({ supplierNo: event }).then(res => {
          if (res.code === 1) {
            this.$set(this.formData, "bank", res.data[0].bank);
            this.$set(this.formData, "bankAccount", res.data[0].bankAccount);
            this.formData.supplierName = res.data[0].supplierName;
          }
        });
      } else {
        return;
      }
    },
    // 切换
    nowselectbuttonindex(index) {
      this.forderStatus = index;
      console.log(this.forderStatus)
      this.currentPage = 1;
      this.search();
    },
    addOrderDetail() {
      this.formData.orderDetailList.push({
        address: "",
        arrivalTime: "",
        castUnitNo: "",
        chandlerName: "",
        confirmQuantity: 1,
        discount: "",
        discountPrice: "",
        materialNo: "",
        packNum: "",
        price: "",
        primaryQuantity: "1",
        stordocNo: "",
        totalPrice: "",
        unitNo: "",
        exchangeRate: "1",
        volume: "",
        weight: "",
        key: Date.now()
      });
    },
    delOrderDetail(index) {
      console.log(this.formData.orderDetailList);
      if (this.formData.orderDetailList.length === 1) {
        return;
      } else {
        this.formData.orderDetailList.splice(index, 1);
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          forderStatus: this.forderStatus,
          completeStatus: false,
          ...this.searchlist,
          startTime: this.searchlist.orderTime
            ? this.searchlist.orderTime + " 00:00:00"
            : "",
          endTime: this.searchlist.orderTime
            ? this.searchlist.orderTime + " 23:59:59"
            : ""
        }
      };
      delete params.entity.orderTime;
      orderApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
          if (this.forderStatus === 0) {
            this.addActive = true;
          } else {
            this.addActive = false;
          }
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.orderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      orderApi.numberBatchDel({ noList: this.selectedStaffList }).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    // 计算主数量相关
    countNum(event, index) {
      console.log(event);
      if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].exchangeRate
      ) {
        this.$set(
          this.formData.orderDetailList[index],
          "primaryQuantity",
          this.formData.orderDetailList[index].confirmQuantity *
            this.formData.orderDetailList[index].exchangeRate
        );
      }
    },
    // 计算价钱相关
    countOnePrice(event, index) {
      if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].price &&
        this.formData.orderDetailList[index].discount
      ) {
        let a =
          (this.formData.orderDetailList[index].confirmQuantity *
            this.formData.orderDetailList[index].price *
            (10 - this.formData.orderDetailList[index].discount)) /
          10;
        let discountPrice = Math.floor(a * 100) / 100;
        this.formData.orderDetailList[index].discountPrice = discountPrice;
        let b =
          this.formData.orderDetailList[index].confirmQuantity *
            this.formData.orderDetailList[index].price -
          discountPrice;
        this.formData.orderDetailList[index].totalPrice =
          Math.floor(b * 100) / 100;
      } else if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].price &&
        !this.formData.orderDetailList[index].discount
      ) {
        let b =
          this.formData.orderDetailList[index].confirmQuantity *
          this.formData.orderDetailList[index].price;
        this.formData.orderDetailList[index].totalPrice =
          Math.floor(b * 100) / 100;
        this.formData.orderDetailList[index].discountPrice = "";
      } else {
        this.formData.orderDetailList[index].totalPrice = "";
        this.formData.orderDetailList[index].discountPrice = "";
      }
      this.countNum(event, index);
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          orderApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      // 获取订单编号
      nowpagereqquery.addcode("ORDER").then(res => {
        this.$set(this.formData, "orderNo", res.data);
      });
      this.formData = {
        orderDetailList: [
          {
            address: "",
            arrivalTime: "",
            castUnitNo: "",
            chandlerName: "",
            confirmQuantity: "",
            discount: "",
            discountPrice: "",
            materialNo: "",
            packNum: "",
            price: "",
            primaryQuantity: "",
            stordocNo: "",
            totalPrice: "",
            unitNo: "",
            exchangeRate: "",
            volume: "",
            weight: ""
          }
        ]
      };
      this.$set(this.formData.orderDetailList[0], "confirmQuantity", 1);
      this.$set(this.formData.orderDetailList[0], "exchangeRate", 1);
      this.$set(this.formData.orderDetailList[0], "primaryQuantity", 1);
      this.$set(this.formData.orderDetailList[0], "packNum", 1);
      this.nowChanceStau = "add";
      this.titleText = "添加采购订单";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      orderDetailApi.numberQuery(row.orderNo).then(res => {
        this.$set(this.formData, "orderDetailList", res.data);
      });
      this.nowChanceStau = "edit";
      this.titleText = "修改采购订单";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    check(row) {
      this.formData = { ...row };
      orderDetailApi.numberQuery(row.orderNo).then(res => {
        this.$set(this.formData, "orderDetailList", res.data);
      });
      this.nowChanceStau = "check";
      this.titleText = "修改订单";
      this.dialogFormVisible = true;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "orderDetailList." + index + ".materialNo",
          "orderDetailList." + index + ".confirmQuantity",
          "orderDetailList." + index + ".castUnitNo",
          "orderDetailList." + index + ".unitNo",
          "orderDetailList." + index + ".exchangeRate",
          "orderDetailList." + index + ".primaryQuantity",
          "orderDetailList." + index + ".price",
          "orderDetailList." + index + ".packNum",
          "orderDetailList." + index + ".totalPrice",
          "orderDetailList." + index + ".address"
        ],
        valid => {
          if (!valid) {
            validateFieldList.push(valid);
            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every(item => item === "")
            ) {
              orderDetailApi.add(e).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  orderDetailApi.numberQuery(e.orderNo).then(res => {
                    this.$set(this.formData, "orderDetailList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          orderDetailApi.edit(e).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => {});
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          orderDetailApi.numberQuery(e.orderNo).then(res => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              orderDetailApi.numberDel(e.orderDetailNo).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.orderDetailList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => {});
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            orderApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            orderApi.add(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          } else if (this.nowChanceStau === "check") {
            orderApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "审核成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "审核失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 140px;
}
.xunhuan {
  margin-top: 20px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }
  .editBox {
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}
.addone {
  margin-left: 140px;
}
.zhu {
  display: flex;
  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}
.numberUnit {
  display: flex;
  .one {
    width: 75%;
  }
  .two {
    width: 25%;
  }
}
</style>
